import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth/next'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    
    if (!session?.user) {
      return NextResponse.json({ message: '未授权访问' }, { status: 401 })
    }

    // 只有教师和管理员可以查看小组信息
    if (session.user.role !== 'TEACHER' && session.user.role !== 'ADMIN') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const experimentId = params.id

    // 验证实验是否存在以及教师是否有权限
    const experiment = await prisma.experiment.findUnique({
      where: { id: experimentId },
      include: { createdBy: true }
    })

    if (!experiment) {
      return NextResponse.json({ message: '实验不存在' }, { status: 404 })
    }

    // 检查权限：实验创建者或管理员
    if (session.user.role !== 'ADMIN' && experiment.createdBy.id !== session.user.id) {
      return NextResponse.json({ message: '您没有权限查看此实验的小组信息' }, { status: 403 })
    }

    // 获取实验的所有小组及其成员信息
    const groups = await prisma.group.findMany({
      where: { experimentId },
      include: {
        members: {
          include: {
            user: {
              select: {
                id: true,
                name: true,
                email: true
              }
            }
          }
        }
      },
      orderBy: { name: 'asc' }
    })

    // 为每个小组成员获取提交信息
    const groupsWithSubmissions = await Promise.all(
      groups.map(async (group: any) => {
        const membersWithSubmissions = await Promise.all(
          group.members.map(async (member: any) => {
            const submission = await prisma.experimentSubmission.findFirst({
              where: {
                studentId: member.user.id,
                experimentId: experimentId
              },
              select: {
                id: true,
                status: true,
                score: true,
                submittedAt: true
              }
            })

            return {
              ...member,
              submission
            }
          })
        )

        return {
          ...group,
          members: membersWithSubmissions
        }
      })
    )

    return NextResponse.json({
      groups: groupsWithSubmissions
    })

  } catch (error) {
    console.error('获取小组信息错误:', error)
    return NextResponse.json(
      { message: '服务器内部错误' },
      { status: 500 }
    )
  }
} 